<template>
  <div v-if="canShowPage" id="userList">
    <h1 class="con-right-title">
      用户管理
    </h1>
    <div class="bottom-box">
      <!--左侧组织机构-->
      <div class="left-tree" :class="isShowLeft ? '' : 'hide-tree'">
        <treeList
          :is-show-left="isShowLeft"
          @checkTreeList="checkTreeList"
        ></treeList>
        <span class="btn-arrow" @click="isShowLeft = !isShowLeft">
          <i
            :class="isShowLeft ? 'el-icon-caret-left' : 'el-icon-caret-right'"
          ></i>
        </span>
      </div>
      <!--右侧table-->
      <div class="right-table" :class="isShowLeft ? '' : 'hide-tree'">
        <!--上部搜索条件组件-->
        <topSearch :form-inline="formInline" @toSearch="toSearch"></topSearch>
        <div class="table-conBtn">
          <el-button
            v-if="powerAry.includes('system:user:import')"
            type="warning"
            class="el-icon-upload2"
            @click="importBtn"
          >
            导入
          </el-button>
          <el-button
            v-if="powerAry.includes('system:user:export')"
            type="warning"
            icon="el-icon-download"
            @click="exportRoles"
          >
            导出
          </el-button>
          <el-button
            v-if="powerAry.includes('system:user:remove')"
            type="warning"
            plain
            @click="delRoles"
          >
            批量删除
          </el-button>
          <freshCom @searchList="searchList"></freshCom>
        </div>
        <!--下部table-->
        <el-table
          v-if="powerAry.includes('system:user:list')"
          v-loading="loading"
          :data="tableData"
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
          max-height="490"
          ref="table"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column
            label="用户ID"
            prop="userId"
            show-overflow-tooltip
            min-width="80"
          ></el-table-column>
          <el-table-column
            label="登录名称"
            prop="loginName"
            min-width="110"
          ></el-table-column>
          <el-table-column
            label="账号昵称"
            prop="userName"
            min-width="100"
          ></el-table-column>
          <el-table-column
            label="部门"
            prop="deptName"
            min-width="120"
          ></el-table-column>
          <!--<el-table-column
            label="邮箱"
            prop="email"
            min-width="120"
          ></el-table-column>-->
          <el-table-column
            label="手机"
            show-overflow-tooltip
            prop="phonenumber"
            width="130"
          ></el-table-column>
          <el-table-column label="用户状态" prop="status" min-width="100">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                active-color="#1DC8A4"
                @change="
                  changeStatus(scope.row.status, scope.row.userId, scope.$index)
                "
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            prop="createTime"
            min-width="160"
          ></el-table-column>
          <el-table-column
            label="最后修改时间"
            prop="updateTime"
            min-width="160"
          ></el-table-column>
          <el-table-column
            label="账号角色"
            prop="roleName"
            min-width="160"
          ></el-table-column>
          <el-table-column
            label="修改人"
            prop="updateBy"
            min-width="160"
          ></el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            :width="powerAry.includes('system:user:resetPwd') ? 150 : 100"
          >
            <template slot-scope="scope">
              <el-button
                v-if="powerAry.includes('system:user:edit')"
                type="text"
                @click="addEditPage(scope.row.userId)"
              >
                编辑
              </el-button>
              <el-button
                v-if="powerAry.includes('system:user:remove')"
                type="text"
                @click="handledelRoles(scope.row.userId)"
              >
                删除
              </el-button>
              <el-button
                v-if="powerAry.includes('system:user:resetPwd')"
                type="text"
                @click="showReset(scope.row.userId, scope.row.loginName)"
              >
                重置
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-全局组件-->
        <pageCom
          :searchParams="searchParams"
          :total="total"
          @searchList="searchList"
        ></pageCom>
      </div>
    </div>
    <!--重置密码弹窗-->
    <resetDialog
      v-if="resetDialogData.isShow"
      :dialog-data="resetDialogData"
      @refresh="refresh"
    ></resetDialog>
  </div>
</template>
<script>
import {
  getSearchList,
  disable,
  enable,
  multipleDel,
  singleDel
} from '@/api/system/user' // 接口
import treeList from '@component/system/user/treeList' // 组织机构
import topSearch from '@component/system/user/topSearch' // 上部搜索条件
import resetDialog from '@component/system/user/dialogResetPass' // 重置密码弹窗
import { saveScrollMixins } from '@/mixins/saveScroll'
export default {
  name: 'userList',
  msg: '用户管理-列表页',
  mixins: [saveScrollMixins],
  components: {
    treeList,
    topSearch,
    resetDialog
  },
  data() {
    return {
      isShowLeft: true,
      loading: true,
      total: 0,
      tableData: [], // table内容
      searchParams: {
        deptId: null,
        parentId: null,
        orderByColumn: '',
        isAsc: '',
        pageNum: 1, // 当前页数
        pageSize: 10 // 页面显示条数
      },
      formInline: {
        // 搜索条件
        userName: '', // 关键字
        phonenumber: '', // 电话
        status: '', // 用户状态,默认所有
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        createTime: []
      },
      resetDialogData: {
        isShow: false, // 控制弹框显示
        userId: null, //用户id
        loginName: '' //登录名称
      },
      multipleSelection: [], // 选中的行
      powerStr: 'system:user:list', // 是否查询的标识
      canGetList: true, // 是否可以查询列表
      powerAry: [], // 可显示的权限
      canShowPage: false // 是否显示当前页面
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.user
    }
  },
  activated() {
    this.toTableScrollHeight()
  },
  mounted() {
    // 获取权限
    // this.getPower()
    this.$nextTick(() => {
      setTimeout(() => {
        this.setTableScrollHeight()
      }, 1000)
    })
  },
  methods: {
    getPower() {
      let id = this.$route.query.mId
      this.getCurPageMenu(id).then((res) => {
        this.powerAry = res
        this.canShowPage = true
        if (!res.includes(this.powerStr)) {
          this.canGetList = false
          this.alertPower(this.powerStr)
        }
        this.searchList()
      })
    },
    /* 获取列表 */
    async searchList() {
      if (!this.canGetList) return
      this.loading = true
      let obj = Object.assign({}, this.searchParams, this.formInline)
      delete obj.createTime
      await getSearchList(
        obj,
        (response) => {
          this.loading = false
          this.tableData = response.rows
          this.total = response.total
        },
        (response) => {
          this.loading = false
          this.$message({
            message: response.message,
            type: 'warning'
          })
        }
      )
    },
    // 状态切换提示
    async changeStatus(status, id, index) {
      // 只有关闭才会弹框
      if (status === '1') {
        // 关闭
        this.$confirm('确认要停用该用户吗？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            disable(id, (response) => {
              this.$message({
                type: 'success',
                message: '已停用'
              })
            })
          })
          .catch(() => {
            this.tableData[index].status = '0'
          })
      } else {
        // 启用
        await enable(id, (response) => {
          this.$message({
            type: 'success',
            message: '已启用'
          })
        })
      }
    },
    // 批量删除
    delRoles() {
      let _this = this
      if (this.multipleSelection.length <= 0) {
        this.$message.warning('请至少选择一条数据！')
        return
      }
      this.$confirm(
        `确认删除选中的这${this.multipleSelection.length}条数据吗？`,
        '删除提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        let ids = []
        this.multipleSelection.forEach((item) => {
          ids.push(item.userId)
        })
        let obj = {
          userIds: ids.join(',')
        }
        multipleDel(obj, (response) => {
          _this.searchList()
        })
      })
    },
    // 删除单个
    handledelRoles(userId) {
      let _this = this
      this.$confirm('确认删除吗？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        singleDel(userId, (response) => {
          _this.searchList()
        })
      })
    },
    showReset(id, loginName) {
      this.resetDialogData.isShow = true
      this.resetDialogData.userId = id
      this.resetDialogData.loginName = loginName
    },
    /* 新增后，刷新列表 */
    refresh() {
      this.toSearch()
    },
    // 导出
    exportRoles() {
      this.$confirm('确定导出所有用户吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(
        () => {
          let url = '/users/export'
          let params = Object.assign({}, this.searchParams, this.formInline)
          delete params.createTime
          delete params.startTime
          delete params.endTime
          this.downFile('get', url, params, '用户管理')
        },
        (response) => {
          this.loading = false
        }
      )
    },
    // checkbox选中事件
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /* 换页 */
    changePage(page) {
      this.searchParams.pageNum = page
      this.searchList()
    },
    /* 搜索 */
    toSearch() {
      this.searchParams.pageNum = 1
      this.searchList()
    },
    /* 跳转编辑页面 */
    addEditPage(id = '') {
      let query = {
        mId: this.$route.query.mId
      }
      if (id) {
        this.$router.push({ name: 'userDetail', params: { id }, query: query })
      } else {
        this.$router.push({ name: 'addUserDetail', query: query })
      }
    },
    /* 选择部门树，执行查询列表 */
    checkTreeList(id, pId) {
      this.searchParams.pageNum = 1
      this.searchParams.deptId = id
      this.searchParams.parentId = pId
      this.searchList()
    }
  }
}
</script>
<style lang="less">
#userList {
  height: 100%;

  .search-box {
    padding-left: 0 !important;
  }
  .table-conBtn {
    padding-left: 0 !important;
  }
  .bottom-box {
    position: relative;
    height: calc(~'100% - 40px');
    .left-tree {
      float: left;
      position: relative;
      width: 192px;
      height: calc(~'100% - 20px');
      overflow: hidden;
      &.hide-tree {
        width: 12px;
      }
      span.btn-arrow {
        position: absolute;
        top: 50%;
        right: 0;
        margin-top: -25px;
        width: 12px;
        height: 50px;
        text-align: center;
        line-height: 50px;
        background: #ddd;
        cursor: pointer;

        &:hover {
          background: #ff8c00;
        }
      }
    }

    .right-table {
      margin-left: calc(~'192px + 20px');

      &.hide-tree {
        margin-left: calc(~'12px + 20px');
      }
    }
  }
}
</style>
